<script>
import Loading from '@/components/Loading';
import Banner from '@/components/Banner';
import CreateEditView from '@/mixins/create-edit-view';
import { exceptionToErrorsArray, stringify } from '@/utils/error';
import { NORMAN } from '@/config/types';
import Questions from '@/components/Questions';
import { iffyFields, simplify } from '@/store/plugins';
import { isEmpty } from '@/utils/object';

export default {
  components: {
    Loading, Banner, Questions
  },

  mixins: [CreateEditView],

  props: {
    credentialId: {
      type:     String,
      required: true,
    },

    provider: {
      type:     String,
      required: true,
    },

    disabled: {
      type:    Boolean,
      default: false
    },
  },

  async fetch() {
    this.errors = [];

    try {
      this.credential = await this.$store.dispatch('rancher/find', { type: NORMAN.CLOUD_CREDENTIAL, id: this.credentialId });
      this.fields = this.$store.getters['plugins/fieldsForDriver'](this.provider);
      const name = `rke-machine-config.cattle.io.${ this.provider }config`;

      if ( !this.fields ) {
        throw new Error(`Machine Driver config schema not found for ${ name }`);
      }
    } catch (e) {
      this.errors = exceptionToErrorsArray(e);
    }
  },

  data() {
    return {
      errors: null,
      fields: null,
    };
  },

  computed: {
    cloudCredentialKeys() {
      const out = [];
      const data = this.credential?.decodedData || {};

      for ( const k in data ) {
        if ( isEmpty(data[k]) || iffyFields.includes(simplify(k)) ) {
          continue;
        }

        out.push(k);
      }

      return out;
    }
  },

  watch: {
    'credentialId'() {
      this.$fetch();
    },
  },

  methods: { stringify },
};
</script>

<template>
  <Loading v-if="$fetchState.pending" :delayed="true" />
  <div v-else-if="errors.length">
    <div
      v-for="(err, idx) in errors"
      :key="idx"
    >
      <Banner
        color="error"
        :label="stringify(err)"
      />
    </div>
  </div>
  <div v-else>
    <Questions
      v-model="value"
      :mode="mode"
      :tabbed="false"
      :source="fields"
      :ignore-variables="cloudCredentialKeys"
      :target-namespace="value.metadata.namespace"
      :disabled="disabled"
    />
  </div>
</template>
